package com.zoo.boot.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zoo.boot.api.CommonResult;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 *
 * @Author: WangB
 * @Date: 2021/6/24
 */
public class CaptchaFilter extends OncePerRequestFilter {
    private String precessUrl = "/login";
    private String method = "post";

    /**
     * 1、从request对象中获取表单提交的验证码
     * 2、再从 session获取验证码
     * 3、比对
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (StrUtil.equals(method, request.getMethod()) && StrUtil.equals(precessUrl, request.getServletPath())) {
            //设置响应头
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            // 从表单中获取验证码
            String captcha = request.getParameter("captcha");
            if (StrUtil.isEmpty(captcha)) {
                response.getWriter().write(JSON.toJSONString(CommonResult.fail("未获取验证码")));
                return;
            }

            String var1 = (String) request.getSession().getAttribute("captcha");
            if (StrUtil.isEmpty(var1)) {
                response.getWriter().write(JSON.toJSONString(CommonResult.fail("验证码已失效")));
                return;
            }

            if (!StrUtil.equals(captcha, var1)) {
                response.getWriter().write(JSON.toJSONString(CommonResult.fail("验证码不正确")));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
